import { request } from "../../request/index"

Page({
  data: {
    leftList: [],/// 左侧数据
    rightList: [], /// 右侧楼层数据
    currentIndex: 0, 
    scrollTop: 0 
  },
  Cates: [],
  /// 生命周期函数
  onLoad: function (options) {
    const Cates = wx.getStorageSync('cates');
    if (!Cates) {
      /// 不存在发送请求
      this.getCates() 
    } else {
      if (Date.now() - Cates.times > 1000 * 10) {
        this.getCates()
      } else {
        this.Cates = Cates.data 
        let leftList = this.Cates.map(v => v.cat_name)
        let rightList = this.Cates[0].children
        this.setData({
          /// 给data里面的变量进行赋值;
          leftList,
          rightList
        })
      }
    }
  },
  async getCates() {
    const res = await request({
      url: '/categories'
    })
    this.Cates = res
    // 把接口请求回来的数据给存到本地;
    wx.setStorageSync('cates', {
      times: Date.now(),
      data: this.Cates
    })
    /// 左边列表数据
    let leftList = this.Cates.map(v => v.cat_name)
    let rightList = this.Cates[0].children
    /// 给data里面的变量进行赋值;
    this.setData({
      leftList,
      rightList
    })
  },
  /// 左侧数据点击
  handleTap(e) {
    /// 获取被点击的下标
    const { index } = e.currentTarget.dataset;
    let rightList = this.Cates[index].children;
    this.setData({
      currentIndex: index,
      rightList,
      //重新设置一下右边的scorll-view的距离顶部的距离
      scrollTop: 0
    })
  }
})
